package com.termux.project

import android.app.Activity
import android.app.NativeActivity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import com.termux.R
import com.termux.frontend.config.NeoTermPath
import org.apache.commons.io.FileUtils
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class IdeaNativeActivity : Activity() {
    // the default native app
    private var nativeApp: String? = "libnative_loader.so"

    // error message
    private var errorMessage: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
            finish()
            return
        }

        // nativeApp = your_project/libxxx.so
        nativeApp = intent.getStringExtra("nativeApp")

        // loading native lib to internal directory
        // to /data/user/0/com.termux.sdl/tmpdir
        if (copyLibFile()) {
            val intent = Intent(this, NativeActivity::class.java)
            // from jni: native_loader.cpp
            intent.putExtra("nativeApp", nativeApp)
            // start native app
            startActivity(intent)
            finish()
        } else {
            setContentView(R.layout.activity_native)
            val textView = findViewById<TextView>(R.id.nativeTextView)
            if (errorMessage == null) errorMessage =
                """
     Failed to load the nativeApp library, the parameters may be wrong.

     Make sure the command is correct.

     am start $(shell am 2>&1| grep -q '\-\-user' && echo '--user 0') -n com.termux.sdl/.TermuxNativeActivity -e nativeApp your_lib_pathname
     """.trimIndent()
            textView.text = errorMessage
        }
    }

    fun copyLibFile(): Boolean {
        if (nativeApp == null || nativeApp!!.isEmpty()) return false
        nativeApp = nativeApp!!.trim { it <= ' ' }
        if (File(nativeApp).exists()) {
            val libDir = NeoTermPath.USR_PATH + "/tmp"
            val libFile = libDir + "/" + File(nativeApp).name
            if (!File(libDir).exists()) {
                File(libDir).mkdir()
            }
            try {
                FileUtils.copyFile(File(nativeApp), File(libFile))
                Runtime.getRuntime().exec("chmod 755 $libFile").waitFor()

                // Environment variables must be set, otherwise the program will not run correctly
                val pwd = intent.getStringExtra("work_dir")
                Log.i(TAG, "chdir: $pwd")
                JNI.chDir(pwd)
                JNI.setEnv("PWD", pwd, true)
                // nativeApp = /data/user/0/com.termux.sdl/tmpdir/libxxx.so
                nativeApp = libFile
                val conf =
                    FileOutputStream("$libDir/native_loader.conf")
                conf.write(nativeApp!!.toByteArray())
                conf.close()
            } catch (ex: IOException) {
                Log.e(
                    TAG,
                    "copy file failed: " + ex.message
                )
                return false
            } catch (ex: InterruptedException) {
                Log.e(
                    TAG,
                    "exec cmd failed: " + ex.message
                )
                return false
            }
        }
        return true
    }

    fun deleteLibFile() {
        // delete /data/user/0/com.termux.sdl/tmpdir/libxxx.so
        if (nativeApp != null && !nativeApp!!.isEmpty()) {
            val file = File(nativeApp)
            if (file.exists()) {
                try {
                    FileUtils.forceDelete(file)
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    override fun onStop() {
        super.onStop()
        deleteLibFile()
    }

    override fun onDestroy() {
        super.onDestroy()
        deleteLibFile()
    }

    companion object {
        private const val TAG = "IdeaNativeActivity"
    }
}